package com.wave.traffic.util;

import com.wave.traffic.enums.NetControllerEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.Socket;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/***
 * @Description
 * @Author chenjian
 * @Date 2022/8/1 18:55
 */
@Slf4j
@Component
public class DelayTaskUtil {

    private static DelayTaskUtil instance;

    private static ScheduledFuture<?> task = null;

    @Autowired
    private ScheduledExecutorService scheduledExecutorService;

    @PostConstruct
    public void init(){
        instance = this;
        instance.scheduledExecutorService = this.scheduledExecutorService;
    }

    public static void execute(Socket netController1,Socket netController2,Socket netController3, Long delay){
        if (task != null) {
            log.info("取消30s后控制器打开人行红灯,打开车辆绿灯的延迟任务");
            task.cancel(true);
            task = null;
        }
        task = instance.scheduledExecutorService.schedule(() -> {
            try {
                log.info("开始执行30s后控制器打开人行红灯,打开车辆绿灯");
                SocketClientUtil.sendData(netController1, NetControllerEnum.WRITE_DO1_OPEN_COMMAND.getCode());
                log.info("控制器213发送人行灯红灯指令,车辆灯绿灯指令-1");
                SocketClientUtil.sendData(netController1, NetControllerEnum.WRITE_DO2_CLOSE_COMMAND.getCode());
                log.info("控制器213发送人行灯红灯指令,车辆灯绿灯指令-2");
                SocketClientUtil.sendData(netController2, NetControllerEnum.WRITE_DO1_CLOSE_COMMAND.getCode());
                log.info("控制器212发送人行灯红灯指令-1");
                SocketClientUtil.sendData(netController3, NetControllerEnum.WRITE_DO1_CLOSE_COMMAND.getCode());
                log.info("控制器215发送人行灯红灯指令-1");
            } catch (Exception e) {
                log.error("延时任务执行异常,e:", e);
                throw new RuntimeException(e);
            }
        }, delay, TimeUnit.MILLISECONDS);

    }
}